import LuchRequest from '@/plugins/luch-request/index.js';
import systemUtils from "@/utils/system/index.js";
import logUtils from "@/utils/log/index.js";
import uniUtils from "@/utils/uni/index.js";

const service = new LuchRequest({
	// baseURL: "https://prodai.xawellcare.com",  // 生产环境
	baseURL: "https://api.xawellcare.com",  // 测试环境
	timeout: 120000
})

class Lock {
	
	constructor() {
		this.flag = false;
		this.data = {};
		this.lockArr = []
	}

	wait() { // 等待锁
		let that_ = this
		let pro = new Promise(resolve => {
			if (this.flag) {
				resolve(this.data);
			} else {
				that_.lockArr.push(resolve)
			}
		});
		return pro
	}

	notify(data = {}) {
		this.data = data;
		this.flag = true;
		for (let i = 0; i < this.lockArr.length; i++) {
			this.lockArr[i](this.data)
		}
		this.lockArr = []
	}
}


var loginHandle = false
const lock = new Lock()

// 请求拦截
service.interceptors.request.use(
	async (request) => {
		if(request.custom.authentication){
			if(!uni.getStorageSync("hospitalId")){
				request.abort();
			}
			let userinfo = uni.getStorageSync('system-userinfo');
			if (!userinfo) {
				if (loginHandle) {
					await lock.wait();
				}
				if (!uni.getStorageSync('system-userinfo')) {
					loginHandle = true
					await systemUtils.login()
					loginHandle = false
				}
				lock.notify()
				userinfo = uni.getStorageSync('system-userinfo');
			} else {
				let nowTime = new Date().getTime();
				if ((userinfo.expiresTime - nowTime) < 300000) {
					if (await systemUtils.login()) {
						userinfo = uni.getStorageSync('system-userinfo');
					}
				}
			}
			request.header = {
				...request.header,
				"hospital-id": uni.getStorageSync("hospitalId"),
				"Authorization": "Bearer " + userinfo.accessToken
			}
		}
		return request
	},
	err => {
		lock.notify();
		logUtils.error(err);
		return Promise.reject(err);
	}
)

// 响应拦截
service.interceptors.response.use(
	(response) => {
		logUtils.request(response);
		if (response.statusCode === 200) {
			if (response.data.code === 0) {
				return response.data.data;
			} else if(response.data.code === 1104001001){
				return Promise.reject(response.data);
			}else {
				uniUtils.toast(response.data.msg);
				return Promise.reject(response.data.msg);
			}
		} else {
			uniUtils.toast("服务忙！");
			return Promise.reject(response.data.msg);
		}
	},
	(error) => {
		logUtils.request(error);
		if(error.toString() !== "TypeError: t.abort is not a function"){
			uniUtils.toast("服务忙！");
		}
		return Promise.reject(error.statusCode);
	}
);

export default service;